using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

using Matchingo.Common.Types.Enumerations;
using Matchingo.Common.Types.Types;
using Matchingo.Common.Types.Interfaces;

using Matchingo.Modules.FacebookHighScoreModule;

namespace Matchingo.Modules.FacebookHighScoreModule.Views
{
	/// <summary>
	/// FacebookHighScoreScreenView XAML codebehind
	/// </summary>
	/// <author>Michael Urvan</author>
	/// <revision>1.0</revision>
	/// <remarks>First added 7/17/09</remarks>
	public partial class FacebookHighScoreView : UserControl, IFacebookHighScoreScreenView
    {
        private const string MENU_SLIDE_IN_RIGHT_STORYBOARD = "SlideInRightStoryboard";
        private const string MENU_SLIDE_OUT_RIGHT_STORYBOARD = "SlideOutRightStoryboard";

        #region ========== Properties ==========

        private FacebookHighScoreScreenViewModel ViewModel { get; set; }

        public UIElement RootElement { get { return LayoutRoot; } }

        #endregion        

        #region ========== Constructors ==========

        public FacebookHighScoreView()
        {            
            InitializeComponent();
        }

        #endregion

        #region ========== Public Methods ==========

		public void Initialize(FacebookHighScoreScreenViewModel model)
        {
            ViewModel = model;
            DataContext = ViewModel;

            SetupSortByComboBox();
            SetupCardCountComboBox();
            
            CardsComboBox.SelectionChanged += CardCountSelectionChanged;
            SortByComboBox.SelectionChanged += SortBySelectionChanged;
            ScoresGrid.SelectionChanged += ScoresGridSelectionChanged;

            ViewModel.PropertyChanged += ViewModel_PropertyChanged;

            RefreshDataSet();
        }

        private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            SelectCardCount(ViewModel.CardCountFilter);
            RefreshDataSet();
        }

        public void ShowScreen(bool skipAnimation)
        {
            PlayStoryboard(MENU_SLIDE_IN_RIGHT_STORYBOARD, skipAnimation);
        }

        public void HideScreen(bool skipAnimation)
        {
            PlayStoryboard(MENU_SLIDE_OUT_RIGHT_STORYBOARD, skipAnimation);
        }

        public void SelectGameRecord(Guid previousGameUniqueID)
        {
            foreach (Game g in ScoresGrid.ItemsSource)
            {
                if (g.UniqueID == previousGameUniqueID)
                {
                    ScoresGrid.SelectedItem = g;
                    ScoresGrid.UpdateLayout();
                    ScoresGrid.ScrollIntoView(g, null);                    
                }
            }
        }

        public void RefreshDataSet()
        {
            // if there is something selected we want to reselect it after we repopulate the grid
            Guid? uniqueGameID = null;
            if (ScoresGrid.SelectedItem != null)
            {
                uniqueGameID = ((Game)ScoresGrid.SelectedItem).UniqueID;
            }

            switch (ViewModel.GameMetricFilter)
            {
                case FacebookHighScoreScreenViewModel.GameMetric.Score:
                    ScoresGrid.ItemsSource = ViewModel.GameRecordsByScore;
                    break;
				case FacebookHighScoreScreenViewModel.GameMetric.Time:
                    ScoresGrid.ItemsSource = ViewModel.GameRecordsByTime;
                    break;
                default:
					throw new ArgumentException("FacebookHighScoreView.RefreshDataSet() - current GameMetricFilter is of unknown type");
            }

            if (uniqueGameID != null)
            {
                // reselect the item
                SelectGameRecord((Guid)uniqueGameID);
            }
        }

        #endregion

        #region ========== Private Methods ==========

        // TODO:: this method is duplicated across all menu views
        private void PlayStoryboard(string storyBoardName, bool skipAnimation)
        {
            Application.Current.RootVisual.Dispatcher.BeginInvoke(() =>
            {
                Storyboard sb = (Storyboard)this.Resources[storyBoardName];
                sb.Begin();
                if (skipAnimation)
                {
                    sb.SkipToFill();
                }
            });
        }

        private void SetupSortByComboBox()
        {
            SortByComboBox.Items.Clear();
			SortByComboBox.Items.Add(FacebookHighScoreScreenViewModel.GameMetric.Score.ToString());
			SortByComboBox.Items.Add(FacebookHighScoreScreenViewModel.GameMetric.Time.ToString());

            SortByComboBox.SelectedIndex = 0;
        }

        private void SetupCardCountComboBox()
        {
            // TODO:: tried binding to a list of ints and using a binding converter, but couldnt get it to work
            CardsComboBox.Items.Clear();
            CardsComboBox.Items.Add("4 Cards");
            CardsComboBox.Items.Add("6 Cards");
            CardsComboBox.Items.Add("12 Cards");
            CardsComboBox.Items.Add("16 Cards");
            CardsComboBox.Items.Add("20 Cards");
            CardsComboBox.Items.Add("24 Cards");
            CardsComboBox.Items.Add("30 Cards");
            CardsComboBox.Items.Add("36 Cards");

            CardsComboBox.SelectedIndex = 2;
        }

        private void SelectCardCount(int cardCount)
        {
            foreach (string cardCountItem in CardsComboBox.Items)
            {
                int count = GetCardCountNumberFromItemString(cardCountItem);
                if (count == cardCount)
                {
                    CardsComboBox.SelectedItem = cardCountItem;
                    return;
                }
            }
        }

        #endregion

        #region ========== Event Handlers ==========

        void ScoresGridSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void CardCountSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;
            
            string countString = e.AddedItems[0].ToString();
            int cardCount = GetCardCountNumberFromItemString(countString);

            ViewModel.CardCountFilter = cardCount;
			ViewModel.LoadHighScoresAsynchronously(10, cardCount);
        }

        private static int GetCardCountNumberFromItemString(string itemString)
        {
            int cardCount;

            // TODO:: this is a hack to be parsing strings from things set in the UI
            int spaceIndex = itemString.IndexOf(' ');
            if (spaceIndex == -1) // there is no space, so it is just the number, return the int
            {
                cardCount = int.Parse(itemString);
            }
            else
            {
                string count = itemString.Substring(0, spaceIndex);
                cardCount = int.Parse(count);
            }

            return cardCount;
        }

        private void SortBySelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;

            ViewModel.SetGameMetricFilter(e.AddedItems[0].ToString());
            
            RefreshDataSet();
        }

        private void ScoresGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {            
            // NOTE:: thanks to sladapter - http://silverlight.net/forums/t/14664.aspx
            e.Row.Header = e.Row.GetIndex() + 1;  // This will write out Row Number
        }

        #endregion

		private void FBUserId_Click(object sender, RoutedEventArgs e)
		{
			if (e.OriginalSource == null)
				return;

			string userId = ((Button)(e.OriginalSource)).Tag.ToString();
			string url = String.Format("http://www.facebook.com/profile.php?id={0}&ref=nf", userId);
			System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(url), "_blank", ""); //toolbar=no,location=no,status=no,menubar=no,resizable=yes
		}

		private void Friends_Clicked(object sender, RoutedEventArgs e)
		{
			ViewModel.ShowFriendsScore();
		}

    }
}
